package com.cg.springSecurity.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cg.springSecurity.pojo.User;
import com.cg.springSecurity.service.UserService;
import com.cg.springSecurity.utils.JwtUtil;
import com.cg.springSecurity.utils.RedisUtils;
import com.cg.springSecurity.vo.Oauth2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cg
 * @date 2023/3/23 15:32
 */
@Controller
@CrossOrigin
@RequestMapping("user")
public class Oauth2Controller {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserService userService;
    @Value("${gitee.client_id}")
    private String clientId;

    @Value("${gitee.client_secret}")
    private String clientSecret;

    @Value("${gitee.client.redirect_uri}")
    private String redirectUri;
    @Value("${gitee.redirect_uri}")
    private String address;//你的前端主页面地址
    //处理code码
    @RequestMapping("oauth2")
    public void oauth2(String code,HttpServletResponse response) {
//        System.out.println("code = " + code);
        Map<String, Object> map = new HashMap<>();
        String url = "https://gitee.com/oauth/token?" +
                "grant_type=authorization_code&code=" + code +
                "&client_id=" + clientId +
                "&redirect_uri=" + redirectUri +
                "&client_secret=" + clientSecret;
        //利用RestTemplate发送post请求
        ResponseEntity<Oauth2Vo> entity = restTemplate.postForEntity(url, null, Oauth2Vo.class);
        Oauth2Vo oauth2Vo = entity.getBody();
        //使用唯一id作为用户名生成token
        String username = "gitee" + oauth2Vo.getCreated_at();
        User user = new User();
        user.setUsername(username);
        user.setPassword(username);
        //未注册则注册
        if (userService.getOne(new QueryWrapper<User>().eq("username",username)) == null) userService.save(user);
        String token = jwtUtil.generate(username);
        if (token != null) {
            redisUtils.set(username, "token");
            try {
                response.sendRedirect(address + token);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

}
